import { Block, View } from "@tarojs/components";
import HtmlToJson from "./libs/html2json";
import React, { useMemo, useState } from "react";
import Taro from "@tarojs/taro";
import WxParseTemplate from "./components/WxParseTemplate";

const RichParse = (props: any) => {
  const {
    className,
    loading = false,
    content = "",
    noData = '<div style="color: red;">数据不能为空</div>',
    startHandler = (node: any) => {
      node.attr.class = null;
      node.attr.style = null;
    },
    endHandler,
    charsHandler,
    imageProp = {
      mode: "aspectFit",
      padding: 0,
      lazyLoad: false,
      domain: "",
    },
    userSelect = "text",
  } = props;
  const [imageUrls, setImageUrls] = useState<string[]>([]);
  const nodes = useMemo(() => {
    const parseData = content || noData;
    const customHandler = {
      start: startHandler,
      end: endHandler,
      chars: charsHandler,
    };
    const results: any = HtmlToJson(parseData, customHandler, imageProp, this);
    setImageUrls(results.imageUrls);
    console.log(results);
    return results.nodes;
  }, [props]);
  const navigate = (href, $event) => {
    // this.$emit("navigate", href, $event);
  };
  const preview = (src, $event) => {
    if (!imageUrls.length) return;
    Taro.previewImage({
      current: src,
      urls: imageUrls,
    });
    // this.$emit("preview", src, $event);
  };
  const removeImageUrl = (src: any) => {
    imageUrls.splice(imageUrls.indexOf(src), 1);
  };
  return (
    !loading && (
      <View className={`wxParse ${className}`}>
        {nodes?.map((item: any, index: number) => (
          <Block key={index}>
            <WxParseTemplate node={item} parseSelect={userSelect} />
          </Block>
        ))}
      </View>
    )
  );
};

export default RichParse;
